﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using GameBase.Form.Control;
using GameBase;
using GameBase.Form;

namespace GalaxyPresident
{
    public class PlayingScreen : GameScreen
    {

        #region STATIC COLOR, NUMBER OF TEAM, GALAXY SIZE
        public static Color BUTTON_COLOR = Color.HotPink;
        public static Color BUTTON_COLOR_1 = Color.Turquoise;
        public static Color BUTTON_COLOR_2 = Color.Gold;
        public static Color BUTTON_COLOR_3 = Color.PaleGreen;
        public static Color COLOR_TEXT_TOOLTIP = Color.White;
        public int MAX_X = 1500;
        public int MAX_Y = 1000;
        
        #endregion
        #region CONTROL
        /// PANELS
        MyPanel messagedBox;
        MyPanel shortPanel;
        MyPanel panel;
        EntityInfoPanel infoPanel;
        SendingPanel sendingPanel;
        MyPanel detailPanel;


        internal EntityInfoPanel InfoPanel
        {
            get { return infoPanel; }
            set { infoPanel = value; }
        }

        MyLabel messagedText;
        MyButton messagedOk;
        MyCombobox planetButton;
        MyCombobox shipButton;
        MyCombobox mailButton;

        MyButton sendButton;
        MyButton sendCancelButton;

        /// BUILDING CONTROL
        MyPanel planetControlPanel;
        MyButton clearButton;
        MyButton oilWellButton;
        MyButton mineButton;
        MyButton researchTowerButton;
        MyButton defenderButton;
        MyButton airPortButton;
        //MyButton capitalButton;

        /// SHIP CONTROL
        MyButton transportButton;
        MyButton warButton;
        //MyButton buildMotherShipButton;

        MyButton upButton;

        MyButton buttonBuildCapital;
        MyButton buttonRetreat;

        private static int MAX_MAIL = 10;
        public static List<Planet> listPlanetInMails = new List<Planet>();

        public static Color PLAYER_COLOR;

        #endregion 
        #region BASIC ATRIBUTES
        private List<Team> _teams = new List<Team>();
        List<SolarSystem> listSolarSystem;

        SolarLayer solarLayer;
        PlanetLayer planetLayer;
        GalaxyLayer galaxyLayer;
        PlayScreenLayer currentLayer;

        public SolarLayer SolarLayer
        {
            get { return solarLayer; }
            set { solarLayer = value; }
        }
                
        public List<Team> Teams
        {
            get { return _teams; }
            set { _teams = value; }
        }

        internal List<SolarSystem> ListSolarSystem
        {
            get { return listSolarSystem; }
            set { listSolarSystem = value; }
        }
        List<AI> listAI= new List<AI>();
        #endregion

        SendTask sendTask;

        #region CONSTRUCTOR, INIT CONTROL, FORM, TEAM, GENARATE SOLARSYSTEMS
        public PlayingScreen(Game1 game, GAME_INFO gameInfo)
            : base(game)
        {
            listPlanetInMails.Clear();

            SolarSystemGenerate(gameInfo);
            initTeam(gameInfo);

            PLAYER_COLOR = _teams[0].TeamColor;

            Planet startPlanet = _teams[0].Planets[0];
            solarLayer = new SolarLayer(this, startPlanet);
            planetLayer = new PlanetLayer(this, startPlanet);
            galaxyLayer = new GalaxyLayer(this, startPlanet);
            currentLayer = planetLayer;
            SendTask.galaxyLayer = galaxyLayer;

            InitMessagedBox();
            InitMenuBar();
            InitPlanetControl();
        }
        private void InitMenuBar()
        {
            upButton = new MyButton(@"Resources/InGame/upButton", new Vector2(Form.Width - 64, 60));
            upButton.Color = BUTTON_COLOR;
            upButton.MouseReleasedCallBack = touchBackButton;
            AddControl(upButton);


            panel = new MyPanel(@"Resources/ingamePanel", Vector2.Zero);
            panel.Color = PANEL_COLOR;
            AddControl(panel);

            planetButton = new MyCombobox(@"Resources/InGame/PlanetButton",
                new Vector2(10, 0));
            planetButton.TextAlign = Align.Right;
            planetButton.ForeColor = Color.White;
            planetButton.MousePressedCallBack = PressedPlanetList;
            planetButton.Segment = 60;
            panel.Add(planetButton);

            shipButton = new MyCombobox(@"Resources/InGame/ShipButton",
                new Vector2(160, 0));
            shipButton.TextAlign = Align.Right;
            shipButton.ForeColor = Color.White;
            shipButton.MousePressedCallBack = PressedShipList;
            shipButton.Segment = 60;
            panel.Add(shipButton);

            mailButton = new MyCombobox(@"Resources/InGame/MailButton",
                new Vector2(310, 0));
            mailButton.Text = "0";
            mailButton.TextAlign = Align.Right;
            mailButton.ForeColor = Color.White;
            mailButton.MousePressedCallBack = PressedMailList;
            mailButton.Segment = 60;
            panel.Add(mailButton);

            MyButton pauseButton = new MyButton(@"Resources/InGame/ExitButton", new Vector2(Form.Width - 64, 0));
            pauseButton.Color = Color.Red;
            pauseButton.MouseReleasedCallBack = PressedPauseButton;
            panel.Add(pauseButton);
            
            ///SHORT PANEL

            shortPanel = new MyPanel(@"Resources/Ingame/shortPanel", Vector2.Zero);
            shortPanel.Color = PANEL_COLOR;
            AddControl(shortPanel);
            shortPanel.Visible = false;

            shortPanel.Add(planetButton);
            shortPanel.Add(shipButton);

            sendCancelButton = new MyButton(@"Resources/InGame/CancelButton",
                new Vector2(0, Form.Height - 200));
            sendCancelButton.Color = Color.Red;
            sendCancelButton.MouseReleasedCallBack= PressedSend;
            shortPanel.Add(sendCancelButton);

            sendButton = new MyButton(@"Resources/Ingame/SendButton",
                new Vector2(200, Form.Height - 200 ));
            sendButton.MouseReleasedCallBack = PressedSend;
            shortPanel.Add(sendButton);

            sendingPanel = new SendingPanel(new Vector2(0, 60));
            shortPanel.Add(sendingPanel);
        }
        private void InitPlanetControl()
        {
            planetControlPanel = new MyPanel(new Vector2(0, Form.Height - 50));
            AddControl(planetControlPanel);
            MyCombobox infoCombo = new MyCombobox(@"Resources/InGame/bInfo",
                Vector2.Zero);
            infoCombo.Color = BUTTON_COLOR;
            infoCombo.ToolTipText = "Infomation";
            infoCombo.ForeColor = COLOR_TEXT_TOOLTIP;
            planetControlPanel.Add(infoCombo);


            /// ================build COMBO
            MyCombobox buildCombo = new MyCombobox(@"Resources/InGame/bBuild",
                new Vector2(50, 0));
            buildCombo.Segment = 50;
            buildCombo.DropDownStyle = false;
            buildCombo.Color = BUTTON_COLOR;
            buildCombo.ToolTipText = "Build";
            buildCombo.ForeColor = COLOR_TEXT_TOOLTIP;
            planetControlPanel.Add(buildCombo);


            clearButton = new MyButton(@"Resources/InGame/bClear",
                Vector2.Zero);
            clearButton.Color = BUTTON_COLOR_2;
            clearButton.MouseReleasedCallBack = PressedBuild;
            clearButton.ToolTipText = "Clear Building";
            clearButton.ForeColor = COLOR_TEXT_TOOLTIP;
            buildCombo.Add(clearButton);

            oilWellButton = new MyButton(@"Resources/InGame/bOilWell",
                Vector2.Zero);
            oilWellButton.Color = BUTTON_COLOR_1;
            oilWellButton.EnableColor = BUTTON_COLOR_1;
            oilWellButton.MouseReleasedCallBack = PressedBuild;
            oilWellButton.ToolTipText = oil.getCostString();
            oilWellButton.ForeColor = COLOR_TEXT_TOOLTIP;
            buildCombo.Add(oilWellButton);

            mineButton = new MyButton(@"Resources/InGame/bmine",
                Vector2.Zero);
            mineButton.Color = BUTTON_COLOR_1;
            mineButton.EnableColor = BUTTON_COLOR_1;
            mineButton.MouseReleasedCallBack = PressedBuild;
            mineButton.ToolTipText = metal.getCostString();
            mineButton.ForeColor = COLOR_TEXT_TOOLTIP;
            buildCombo.Add(mineButton);


            researchTowerButton = new MyButton(@"Resources/InGame/bResearchTower",
                Vector2.Zero);
            researchTowerButton.Color = BUTTON_COLOR_1;
            researchTowerButton.EnableColor = BUTTON_COLOR_1;
            researchTowerButton.MouseReleasedCallBack = PressedBuild;
            researchTowerButton.ToolTipText = scien.getCostString();
            researchTowerButton.ForeColor = COLOR_TEXT_TOOLTIP;
            buildCombo.Add(researchTowerButton);

            defenderButton = new MyButton(@"Resources/InGame/bDefender",
                Vector2.Zero);
            defenderButton.Color = BUTTON_COLOR_1;
            defenderButton.EnableColor = BUTTON_COLOR_1;
            defenderButton.MouseReleasedCallBack = PressedBuild;
            defenderButton.ToolTipText = miss.getCostString();
            defenderButton.ForeColor = COLOR_TEXT_TOOLTIP;
            buildCombo.Add(defenderButton);

            airPortButton = new MyButton(@"Resources/InGame/bAirPort",
                Vector2.Zero);
            airPortButton.Color = BUTTON_COLOR_1;
            airPortButton.EnableColor = BUTTON_COLOR_1;
            airPortButton.MouseReleasedCallBack = PressedBuild;
            airPortButton.ToolTipText = airp.getCostString();
            airPortButton.ForeColor = COLOR_TEXT_TOOLTIP;
            buildCombo.Add(airPortButton);

            //capitalButton = new MyButton(@"Resources/InGame/bCapital",
            //    Vector2.Zero);
            //capitalButton.Color = BUTTON_COLOR_1;
            //capitalButton.EnableColor = BUTTON_COLOR_1;
            //capitalButton.MouseReleasedCallBack = PressedBuild;
            //buildCombo.Add(capitalButton);



            ///==============ship COMBO
            MyCombobox shipCombo = new MyCombobox(@"Resources/InGame/bShip",
                new Vector2(100, 0));
            shipCombo.Color = BUTTON_COLOR;
            shipCombo.Segment = 50;
            shipCombo.DropDownStyle = false;
            shipCombo.ToolTipText = "MotherShip";
            shipCombo.ForeColor = COLOR_TEXT_TOOLTIP;
            planetControlPanel.Add(shipCombo);
            
            /*buildMotherShipButton = new MyButton(@"Resources/InGame/bMotherShip",
                Vector2.Zero);
            buildMotherShipButton.Color = BUTTON_COLOR_3;
            buildMotherShipButton.MouseReleasedCallBack = BuildMotherShipCallBack;
            //researchButton.MouseReleasedCallBack = PressedShipControl;
            shipCombo.Add(buildMotherShipButton);*/
            
            warButton = new MyButton(@"Resources/InGame/bWar",
                Vector2.Zero);
            warButton.Color = BUTTON_COLOR_2;
            warButton.MouseReleasedCallBack = PressedShipControl;
            warButton.ToolTipText = "War";
            warButton.ForeColor = COLOR_TEXT_TOOLTIP;
            shipCombo.Add(warButton);

            transportButton = new MyButton(@"Resources/InGame/bTransport",
                Vector2.Zero);
            transportButton.Color = BUTTON_COLOR_1;
            transportButton.MouseReleasedCallBack = PressedShipControl;
            transportButton.ToolTipText = "Send Item";
            transportButton.ForeColor = COLOR_TEXT_TOOLTIP;
            shipCombo.Add(transportButton);

            InfoPanel = new EntityInfoPanel(new Vector2(Form.Width-300, Form.Height - 500));
            InfoPanel.Color = PANEL_COLOR;
            InfoPanel.Visible = false;
            InfoPanel.ShowDetailPanelEvent = showDetailPanel;
            AddControl(InfoPanel);

            detailPanel = new MyPanel(@"Resources/contentpanel", new Vector2(200, 200));
            detailPanel.Add(new MyLabel(new Vector2(100,50), (new SpaceCraft(planetLayer.Planet)).getUnitInfoString(),FORCOLOR));
            //detailPanel.Add(new MyLabel(new Vector2(100, 400), (new AirCraft(planetLayer.Planet)).getUnitInfoString(), FORCOLOR));
            //detailPanel.Add(new MyLabel(new Vector2(100, 600), (new BomberCraft(planetLayer.Planet)).getUnitInfoString(), FORCOLOR));
            detailPanel.Visible = false;
            detailPanel.Color = PANEL_COLOR;            
            AddControl(detailPanel);

            buttonBuildCapital = new MyButton(@"Resources/InGame/bCapital", new Vector2(0, form.Height - 50));
            buttonBuildCapital.Color = BUTTON_COLOR_1;
            buttonBuildCapital.EnableColor = BUTTON_COLOR_1;
            buttonBuildCapital.MouseReleasedCallBack = PressedBuild;
            buttonBuildCapital.Visible = false;
            buttonBuildCapital.ToolTipText = "Build capital";
            buttonBuildCapital.ForeColor = COLOR_TEXT_TOOLTIP;
            AddControl(buttonBuildCapital);

            buttonRetreat = new MyButton(@"Resources/InGame/bRetreat", new Vector2(55, form.Height - 50));
            buttonRetreat.Color = BUTTON_COLOR_1;
            buttonRetreat.EnableColor = BUTTON_COLOR_1;
            buttonRetreat.MouseReleasedCallBack = PressedBuild;
            buttonRetreat.Visible = false;
            buttonRetreat.ToolTipText = "Retreat";
            buttonRetreat.ForeColor = COLOR_TEXT_TOOLTIP;
            AddControl(buttonRetreat);
        }
        private void InitMessagedBox()
        {
            messagedBox = new MyPanel(@"Resources/InGame/messagedBox",
                new Vector2((Form.Width - 600) / 2, (Form.Height - 450) / 2));
            messagedBox.Color = PANEL_COLOR;
            messagedBox.Visible = false;
            messagedText = new MyLabel(new Vector2(300, 100), "Do you want to quit?", GameScreen.FORCOLOR);
            messagedText.TextAlign = Align.Center;
            messagedText.Font = Constant.fontNormalBold;
            messagedBox.Add(messagedText);

            messagedOk = new MyButton(new Vector2(50, 350), "OK");
            messagedOk.SetRandomColor();
            messagedOk.MouseReleasedCallBack = PressedOKButton;
            messagedBox.Add(messagedOk);


            MyButton messagedCancel = new MyButton(new Vector2(350, 350), "Cancel");
            messagedCancel.SetRandomColor();
            messagedCancel.MouseReleasedCallBack = PressedCancelButton;
            messagedBox.Add(messagedCancel);

            AddControl(messagedBox);
        }
        private void initTeam(GAME_INFO gameInfo)
        {
            // init team
            for (int i = 0; i < gameInfo.numberOfTeam; i++)
            {
                Team team = new Team();
                team.TotalMoney = gameInfo.moneyAmount;
                _teams.Add(team);
                if (i > 0)
                {
                    AI teamAI = new AI(team);
                    listAI.Add(teamAI);
                }
            }
            AI.solarSystems = listSolarSystem;
            // init team color
            int index = 1;
            _teams[0].TeamColor = Constant.teamColors[gameInfo.myColorIndex];
            for (int i = 0; i < Constant.teamColors.Length; i++)
            {
                if(i != gameInfo.myColorIndex)
                    _teams[index++].TeamColor = Constant.teamColors[i];
                if (index >= _teams.Count)
                    break;
            }

            // init team's planet
            List<SolarSystem> ss = getLivaleSolarSystem(listSolarSystem);
            if (ss.Count < _teams.Count)
            {
                throw new Exception(@"Number of livable solar sys is less than number of teams. So can't generate planet for team !");
            }
            for (int i = 0; i < _teams.Count; i++)
            {
                List<Planet> livablePlanets = getListLivablePlanetInLivableSolarSystem(ss[i]);
                int random = Constant.random.Next(livablePlanets.Count);
                _teams[i].Planets.Add(livablePlanets[random]);
                livablePlanets[random].TeamOwner = _teams[i];
                livablePlanets[random].autoAddNewEntityAtBlock(new Capital(livablePlanets[random], _teams[i]), 0);

                //if (livablePlanets.Count > 1)
                //{
                //    random = Constant.random.Next(livablePlanets.Count);
                //    _teams[i].Planets.Add(livablePlanets[1]);
                //    livablePlanets[1].TeamOwner = _teams[i];
                //}
            }


        }

        private List<SolarSystem> getLivaleSolarSystem(List<SolarSystem> solarsyss)
        {
            List<SolarSystem> result = new List<SolarSystem>();
            foreach (SolarSystem ss in solarsyss)
            {
                foreach (Planet planet in ss.Planets)
                {
                    if (planet.GetType() == typeof(LivalePlanet))
                    {
                        result.Add(ss);
                        break;
                    }
                }
            }
            return result;
        }

        private List<Planet> getListLivablePlanetInLivableSolarSystem(SolarSystem ss)
        {
            List<Planet> result = new List<Planet>();
            foreach (Planet planet in ss.Planets)
            {
                if (planet.GetType() == typeof(LivalePlanet))
                {
                    result.Add(planet);
                }
            }
            return result;
        }

        private void SolarSystemGenerate(GAME_INFO gameInfo)
        {
            listSolarSystem = new List<SolarSystem>();
            for (int i = 0; i < gameInfo.numberOfSolarSystem; i++)
            {
                MAX_X = (int)(Math.Sqrt( gameInfo.numberOfSolarSystem )* 500);
                MAX_Y = (int)(MAX_X * 0.75);
                int x, y;
                bool available = true;
                //int loop = 0;
                do
                {
                    x = (int)((Constant.random.Next(2 * MAX_X) - MAX_X));
                    y = (int)((Constant.random.Next(2 * MAX_Y) - MAX_Y));
                    available = true;
                    int minD = 200;
                    for (int j = 0; j < listSolarSystem.Count; j++)
                    {
                        float dx = listSolarSystem[j].Position.X - x;
                        float dy = listSolarSystem[j].Position.Y - y;
                        if (dx * dx + dy * dy < minD * minD)
                        {
                            available = false;
                            break;
                        }
                    }
                } while ((float)(x * x) / (MAX_X * MAX_X) +
                    (float)(y * y) / (MAX_Y * MAX_Y) > 1 ||
                    !available);

                string name ;
                do
                {
                    available = true;
                    name = SolarSystem.NAMEPRE[
                        Constant.random.Next(SolarSystem.NAMEPRE.Length)];
                    name += SolarSystem.NAMESUF[
                        Constant.random.Next(SolarSystem.NAMESUF.Length)];
                    for (int j = 0; j < listSolarSystem.Count; j++)
                    {
                        if (listSolarSystem[j].Name == name)
                        {
                            available = false;
                            break;
                        }
                    }
                } while (!available);
                SolarSystem ss = new SolarSystem(gameInfo, name,
                    new Vector3(x, y, Constant.random.Next(100)),
                        (float)(Constant.random.NextDouble() * 0.3 + 0.7));

                ss.Color = Constant.starColors[
                    Constant.random.Next(Constant.starColors.Length)];
                listSolarSystem.Add(ss);
            }
        }
        #endregion
        #region SHOWLAYER
        public void ShowSolarLayer(SolarSystem ss, bool isZoom)
        {

            SolarLayer.SetSolarSystem(ss, isZoom);
            currentLayer = SolarLayer;
        }
        public void ShowPlanetLayer(Planet planet)
        {
            currentLayer = planetLayer;
            planetLayer.SetPlanet(planet);
            InfoPanel.Visible = false;
            if (planet.TeamOwner == Teams[0])
            {
                planetControlPanel.Visible = true;
            }
            else if (currentLayer == planetLayer)
            {
                planetControlPanel.Visible = false;
            }

            if (sendTask != null)
            {
                sendTask.Target = planetLayer.Planet;
                if (sendTask.isAvailable(planetControlPanel.Visible))
                {
                    sendButton.Color = sendTask.GetColor();
                    sendButton.Visible = true;
                }
                planetControlPanel.Visible = false;
            }
        }
        public void backToPreviousLayer()
        {

            if (currentLayer == planetLayer)
            {
                SolarSystem ss = planetLayer.Planet.SolarSystem;
                if (ss != SolarLayer.SolarSystem)
                {
                    ShowSolarLayer(ss, false);
                }
                else
                {
                    SolarLayer.ResetView();
                    currentLayer = SolarLayer;
                }
            }
            else if (currentLayer == SolarLayer)
            {
                SolarSystem ss = SolarLayer.SolarSystem;

                galaxyLayer.Focus(ss);
                currentLayer = galaxyLayer;
            }
            planetControlPanel.Visible = false;
            InfoPanel.Visible = false;
            sendButton.Visible = false;
        }
        #endregion

        public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            base.Draw(gameTime, spriteBatch);
            currentLayer.Draw(gameTime, spriteBatch);
            if (sendTask != null)
            {
                string text = "Select Planet to " + sendTask.Name;
                Text.Draw(spriteBatch, text, Constant.fontNormalBold,
                    450*Form.ScreenScale.X, 5,
                    new Color(1f, 1f, 1f,0.3f), new Color(0.0f, 0.5f, 0.0f,0.3f));                
            }
        }
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            
            currentLayer.Update(gameTime);
            foreach (SolarSystem ss in listSolarSystem)
            {
                //ss.Update(gameTime);
                ss.UpdateInfo(gameTime);
            }
            planetButton.Text = _teams[0].Planets.Count.ToString();
            shipButton.Text = _teams[0].getAllMotherShipAreWorking().Count.ToString();
            mailButton.Text = listPlanetInMails.Count.ToString();

            foreach (Team team in _teams)
                team.UpdateInfo(gameTime);
            
            updateButtonsState();
            infoPanel.UpdateInfo(gameTime);

            updateBuildCapitalButtonAndRetreatButton();

            if (isSendTaskMode)
            {
                sendingPanel.Visible = (currentLayer == planetLayer);
            }
        }

        private void updateBuildCapitalButtonAndRetreatButton()
        {
            if (currentLayer == planetLayer
                && planetLayer.Planet.TeamOwner != Teams[0]
                && _teams[0].isHaveMotherShipAtPlanet(planetLayer.Planet))
            {
                buttonBuildCapital.Visible = true;
                buttonRetreat.Visible = true;
                buttonBuildCapital.IsEnable = _teams[0].isHaveMotherShipEnoughResourceForBuildCapitalAtPlanet(planetLayer.Planet);
            }
            else
            {
                buttonBuildCapital.Visible = false;
                buttonRetreat.Visible = false;
                if (currentLayer == planetLayer
                && planetLayer.Planet.TeamOwner == Teams[0])
                {
                    planetControlPanel.Visible = true;
                }
            }
        }

        #region OVERRITE MOUSE, KEYBOARD
        protected override void HandleKeyBoard()
        {
            base.HandleKeyBoard();
            currentLayer.HandleKeyBoard();
        }
        protected override void MouseHandle()
        {
            currentLayer.MouseHandle();
        }
        protected override void MousePressed(bool onForm)
        {
            base.MousePressed(onForm);
            currentLayer.MousePressed(onForm);
        }
        protected override void MouseReleased(bool onForm)
        {
            base.MouseReleased(onForm);
            currentLayer.MouseReleased(onForm);
        }
        #endregion

        private bool isSendTaskMode = false;
        private void SetShortPanel(bool show)
        {
            isSendTaskMode = show;
            panel.Visible = !show;
            shortPanel.Visible = show;
        }

        #region COMPLETED CALLBACK ( DO NOT TOUCH)
        private void touchBackButton(MyControl sender)
        {
            backToPreviousLayer();
        }
        private void PressedPauseButton(MyControl sender)
        {
            messagedBox.Visible = true;
        }
        private void PressedOKButton(MyControl sender)
        {
            foreach (AI ai in listAI)
            {
                ai.IsLive = false;
            }
            game.State = new MainMenuScreen(game);
            messagedBox.Visible = false;
        }

        private void PressedCancelButton(MyControl sender)
        {
            messagedBox.Visible = false;
        }

        private void PressedPlanetList(MyControl sender)
        {
            planetButton.RemoveAll();
            foreach (Planet planet in _teams[0].Planets)
            {
                planetButton.Add(new PlanetItemControl(this,planet));
            }
        }

        private void PressedShipList(MyControl sender)
        {
            shipButton.RemoveAll();
            List<MotherShip> listMotherShipAreWorking = _teams[0].getAllMotherShipAreWorking();
            foreach (MotherShip mothershipzzz in listMotherShipAreWorking)
            {
                shipButton.Add(new PlanetItemControl(this, mothershipzzz.PlanetOwner));
            }
        }

        private void PressedMailList(MyControl sender)
        {
            mailButton.RemoveAll();
            foreach (Planet planet in listPlanetInMails)
            {
                mailButton.Add(new PlanetItemControl(this, planet));
            }
        }

        private void PressedBuild(MyControl sender)
        {
            if (sender == clearButton)
            {
                planetLayer.SetConstruction(new ClearTask());
            }
            else if (sender == buttonRetreat)
            {
                List<MotherShip> listMotherships = _teams[0].getAllMotherShipAtPlanet(planetLayer.Planet);
                foreach (MotherShip mothershipzzz in listMotherships)
                    mothershipzzz.retreat();
            }
            else
            {
                OwnEntity building;
                if (sender == oilWellButton)
                {
                    building = new OilWell(planetLayer.Planet);
                }
                else if (sender == mineButton)
                {
                    building = new MeterialExploit(planetLayer.Planet);
                }
                else if (sender == researchTowerButton)
                {
                    building = new ScienceTower(planetLayer.Planet);
                }
                else if (sender == defenderButton)
                {
                    building = new MissileDeffend(planetLayer.Planet);
                }
                else if (sender == airPortButton)
                {
                    building = new AirPort(planetLayer.Planet);
                }
                else
                {
                    building = new Capital(planetLayer.Planet, _teams[0]);
                }
                planetLayer.SetConstruction(new BuildingTask(building));
            }
        }
        private void PressedShipControl(MyControl sender)
        {
            SetShortPanel(true);
            //if (sender == buildMotherShipButton)
            //{
            //    sendTask = new SendResearchTask(planetLayer.Planet);
            //}
            /*else */if (sender == transportButton)
            {
                sendTask = new SendItemTask(planetLayer.Planet);
            }
            else if (sender == warButton)
            {
                sendTask = new SendWarTask(planetLayer.Planet);
            }
            solarLayer.DefaultInfoType = InfomationType.Brief;
            sendingPanel.Set(planetLayer.Planet);
            backToPreviousLayer();

        }
        private void PressedSend(MyControl sender)
        {
            SetShortPanel(false);
            if (sendTask != null)
            {
                Planet source = sendTask.Source;
                
                if (sender == sendButton)
                {
                    sendTask.MotherShip = Teams[0].GetMotherShip(source);
                    sendTask.SendingInfo = sendingPanel.GetInfo();
                    if (sendTask.Execute())
                    {
                        
                    }
                }
                
                sendTask = null;
                ShowPlanetLayer(source);
                sendButton.Visible = false;
            }
            solarLayer.DefaultInfoType = InfomationType.None;
        }
        #endregion

        private void BuildMotherShipCallBack(MyControl sender)
        {
            Teams[0].MotherShips.Add(new MotherShip(planetLayer.Planet));
        }

       
        #region Update disable button if not enough resource
        OilWell oil = new OilWell(null);
        MeterialExploit metal = new MeterialExploit(null);
        AirPort airp = new AirPort(null);
        ScienceTower scien = new ScienceTower(null);
        //Capital cap = new Capital(null);
        MissileDeffend miss = new MissileDeffend(null);
        private void updateButtonsState()
        {
            oilWellButton.IsEnable = planetLayer.Planet.isEnoughResourcesForProduce(oil);
            mineButton.IsEnable = planetLayer.Planet.isEnoughResourcesForProduce(metal);
            researchTowerButton.IsEnable = planetLayer.Planet.isEnoughResourcesForProduce(scien);
            defenderButton.IsEnable = planetLayer.Planet.isEnoughResourcesForProduce(miss);
            airPortButton.IsEnable = planetLayer.Planet.isEnoughResourcesForProduce(airp);
            //capitalButton.IsEnable = planetLayer.Planet.isEnoughResourcesForProduce(cap);
            //buttonBuildCapital.IsEnable = planetLayer.Planet.isEnoughResourcesForProduce(cap);

            bool haveMotherShip =(Teams[0].GetMotherShip(planetLayer.Planet) != null); 
            warButton.IsEnable = haveMotherShip;
            transportButton.IsEnable = haveMotherShip;

            //if(haveMotherShip)
            //buttonBuildCapital.IsEnable = 
        }
        #endregion

        public void showDetailPanel()
        {
            detailPanel.Visible = true;
        }

        public override void OnCloseGame()
        {
            foreach (AI ai in listAI)
            {
                ai.IsLive = false;
            }
        }

        public static void addNewPlanetMail(Planet planet)
        {
            if (listPlanetInMails.Count >= MAX_MAIL)
                listPlanetInMails.RemoveAt(MAX_MAIL - 1);
            listPlanetInMails.Insert(0, planet);
        }
    }
}
